<template>
	<div>
		<el-form size="small" :model="form" :rules="rules" ref="ruleForm" label-width="100px">
			<el-form-item label="签到活动：" prop="is_open">
				<el-radio v-model="form.is_open" :label="true">开启</el-radio>
				<el-radio v-model="form.is_open" :label="false">关闭</el-radio>
			</el-form-item>
			<div class="open-sign">
				<span class="gray9">开启后，客户可在每日签到页面进行签到</span>
			</div>
			<el-form-item label="签到模式：" prop="sign_type">
				<el-radio v-model="form.sign_type" label="0">无限制</el-radio>
				<el-radio v-model="form.sign_type" label="1">周循环</el-radio>
				<el-radio v-model="form.sign_type" label="2">月循环</el-radio>
			</el-form-item>
			<div class="open-sign">
				<span class="gray9">无限制，累积和连续签到不会清零，周循环，每周一会清理连续的记录为0，重新开启计算，月循环，每月一号会清理连续的记录为0，重新开启计算</span>
			</div>
			<div v-if="form.is_open" class="mt16">
				<el-form-item label="每日签到：" prop="ever_sign">
					<div class="d-s-s d-c bg_coupon" style="width: 100%;">
						<el-form-item label-width="auto" label="赠送优惠券">
							<el-radio-group v-model="form.is_coupon">
								<el-radio :label="true">开启</el-radio>
								<el-radio :label="false">关闭</el-radio>
							</el-radio-group>
						</el-form-item>
						<div style="width: 100%" class="mb16" v-if="form.is_coupon == true">
							<el-button type="primary" @click="addCoupon('coup')" class="mb16"
								icon="Plus">添加优惠劵</el-button>
							<el-table border :data="coupon_list" style="width: 100%" class="">
								<el-table-column prop="coupon_id" label="优惠券ID">
								</el-table-column>
								<el-table-column prop="name" label="优惠券名称">
								</el-table-column>
								<el-table-column label="赠送张数">
									<template #default="scope">
										<el-form-item style="margin-bottom: 0;">
											<el-input type="number" v-model="form.coupon[scope.$index].coupon_num">
												<template #append>张</template>
											</el-input>
										</el-form-item>
									</template>
								</el-table-column>
								<el-table-column prop="address" label="操作">
									<template #default="scope">
										<el-button type="primary" size="small" link @click="delcoupon(scope.row)">
											删除
										</el-button>
									</template>
								</el-table-column>
							</el-table>

						</div>
						<el-form-item label-width="auto" label="赠送积分" class="">
							<el-input v-model="form.ever_sign" placeholder="请输入赠送积分" type="number" min="0">
								<template #append>积分</template></el-input>
						</el-form-item>
					</div>
					<div class="mt16 mb16 d-s-c">
						<span class="mr10">递增奖励</span>
						<el-radio v-model="form.is_increase" :label="true">开启</el-radio>
						<el-radio v-model="form.is_increase" :label="false">关闭</el-radio>
					</div>
					<div v-if="form.is_increase" class="bg_coupon p-0-20 pt16" style="width: 100%;">
						<el-form-item label-width="auto" label="第二天起递增奖励" prop="increase_reward">
							<div class="d-s-c">
								<div>
									<el-input v-model="form.increase_reward" placeholder="请输入第二天起递增积分数"
										style="width: 180px" min="0" type="number"></el-input>
								</div>
								<span class="ml10">积分</span>
							</div>
						</el-form-item>
						<el-form-item label="第" label-width="auto" prop="no_increase">
							<div class="d-s-c">
								<div>
									<el-input-number :controls="false" style="width: 180px;text-align: left;" :min="2"
										v-model="form.no_increase" placeholder="请输入第几天不再递增" :step="1" step-strictly />
									<!-- 	<el-input v-model="form.no_increase" placeholder="请输入第几天不再递增" min="2"
										style="width: 180px" type="number"></el-input> -->
								</div>
								<span class="ml10">天起不再递增</span>
							</div>
						</el-form-item>
					</div>
					<div class="gray9">用户可在签到页每日签到一次，签到后可获得每日签到奖励</div>
				</el-form-item>


				<el-form-item label="连续签到：" prop="is_open">
					<div class="gray9">用户连续签到指定天数后会获得奖励，断签则重新计算（不重复发放日签奖励）</div>
					<div class="reward-list" style="width: 100%">
						<div class="reward-item pr" v-for="(item, reward_index) in form.reward_data"
							:key="reward_index">
							<div class="d-b-c mb16">
								<span class="ml10">连续签到规则{{ reward_index + 1 }}</span>
								<el-button class="delete-reward" @click="deleteRewardClick(reward_index)" type="primary"
									size="small" link>删除</el-button>
							</div>

							<el-form-item label-width="auto" label="签到天数" :prop="'reward_data.' + reward_index + '.day'"
								:rules="rules.day">
								<div class="d-s-c">
									<div>
										<el-input v-model="item.day" placeholder="请输入连续签到天数" class="max-w460"
											type="number" min="0"><template #prepend>连续签到</template>
											<template #append>天</template></el-input>
									</div>
								</div>
							</el-form-item>
							<el-form-item label="" label-width="auto">
								<div class="d-s-s d-c" style="width: 100%">
									<div class="">
										<el-checkbox v-model="item.is_coupon">赠送优惠劵</el-checkbox>
										<el-checkbox v-model="item.is_point">赠送积分</el-checkbox>
									</div>
									<div class="mb16" style="width: 100%" v-if="item.is_coupon">
										<el-button type="primary" @click="addCoupon('coup_sum', reward_index)"
											class=" mb16" icon="Plus">添加优惠劵</el-button>
										<el-table border :data="item.coupon" style="width: 100%" class="">
											<el-table-column prop="coupon_id" label="优惠券ID">
											</el-table-column>
											<el-table-column prop="name" label="优惠券名称">
											</el-table-column>
											<el-table-column label="赠送张数">
												<template #default="scope">
													<el-form-item style="margin-bottom: 0;">
														<el-input type="number"
															v-model="item.coupon[scope.$index].coupon_num">
															<template #append>张</template>
														</el-input>
													</el-form-item>
												</template>
											</el-table-column>
											<el-table-column prop="address" label="操作">
												<template #default="scope">
													<el-button type="primary" size="small" link
														@click="delcoupons(reward_index, scope.$index)">
														删除
													</el-button>
												</template>
											</el-table-column>
										</el-table>

									</div>
									<el-form-item label-width="auto" label="赠送积分" v-if="item.is_point" class="mb16">
										<el-input v-model="item.point" placeholder="请输入赠送积分" type="number" min="0"
											style="width: 200px">
											<template #append>积分</template></el-input>
									</el-form-item>
								</div>
							</el-form-item>
						</div>
					</div>
					<el-button type="primary" size="small" icon="Plus" @click="addReward">添加连续签到规则</el-button>
				</el-form-item>
				<!--规则-->
				<el-form-item label="规则说明：">
					<WangEditor style="width: 375px" :content="contents" @contens="contentm"
						@editorContent="getEditorContent"></WangEditor>
				</el-form-item>
			</div>
			<!--提交-->
			<div class="common-button-wrapper">
				<el-button type="primary" size="small" @click="onSubmit" :disabled="loading">提交</el-button>
			</div>
		</el-form>
		<GetCoupon v-if="open_add" :open_add="open_add" :type="1" @closeDialog="closeProductDialogFunc($event)">选择优惠券弹出层
		</GetCoupon>
	</div>
</template>
<script>
	import {
		getData,
		saveData
	} from '@/api/sign.js';
	import GetCoupon from "@/components/coupon/GetCoupon.vue";
	import WangEditor from "@/components/wangEditor/index.vue";
	export default {
		components: {
			/*编辑器*/
			WangEditor,
			GetCoupon
		},
		data() {
			/*判断额外奖励*/
			let validate_reward_data = (rule, value, callback) => {
				if (value.length < 1) {
					callback(new Error('请添加至少一项额外奖励！'));
				} else {
					callback();
				}
			};

			/*连续签到天数*/
			let validate_day = (rule, value, callback) => {
				if (this.form.reward_data.lenght < 1) {
					callback();
				} else {
					if (value === '') {
						callback(new Error('天数不能为空！'));
					}
					callback();
				}
			};

			/*连续签到天数的积分数*/
			let validate_point = (rule, value, callback) => {
				if (value === '') {
					callback(new Error('请输入连续签到积分数！'));
				} else {
					callback();
				}
			};

			return {
				contents: "",
				/*富文本配置*/
				ueditor: {
					text: '',
					config: {
						initialFrameWidth: 400,
						initialFrameHeight: 500
					}
				},
				/*表单数据对象*/
				form: {
					is_open: false,
					is_increase: false,
					increase_reward: 0,
					no_increase: 0,
					ever_sign: 0,
					reward_data: [],
					coupon: [],
					is_coupon: true,
					sign_type: "",
				},
				coupon_list: [],
				coupon_name: '',
				coupon_index: '',
				open_add: false,
				/*是否正在加载*/
				loading: true,
				loadings: false,
				/*验证规则*/
				rules: {
					/*每日签到*/
					ever_sign: [{
						required: true,
						message: '每日签到送积分有误',
						trigger: 'blur'
					}],
					/*第二天起递增*/
					increase_reward: [{
						required: true,
						message: '请输入第二天起递增积分数',
						trigger: 'blur'
					}],
					/*第几天不再递增*/
					no_increase: [{
						required: true,
						message: '请输入第几天不再递增',
						trigger: 'blur'
					}],
					/*连续签到额外奖励*/
					reward_data: [{
						validator: validate_reward_data,
						required: true,
						trigger: 'blur'
					}],
					/*连续签到*/
					day: [{
						validator: validate_day,
						required: true,
						trigger: 'blur'
					}],
					/*连续签到积分数*/
					point: [{
						validator: validate_point,
						required: true,
						trigger: 'blur'
					}],
				}
			};
		},
		created() {
			/*获取列表*/
			this.getData();
		},
		methods: {
			contentm(e) {
				this.contents = e;
			},
			getEditorContent(data) {
				console.log(data, "dtat");
				this.content = data;
			},
			addCoupon(name, index) {
				this.coupon_name = name;
				this.coupon_index = index;
				this.open_add = true;
			},
			/*关闭优惠券*/
			closeProductDialogFunc(e) {
				let self = this;
				self.open_add = e.openDialog;
				if (self.coupon_name == "coup") {
					if (e.type == "success") {
						if (self.form.coupon == null) {
							self.form.coupon = [];
						}
						if (self.form.coupon.length < 1) {
							self.form.coupon.push({
								coupon_id: e.params.coupon_id,
								name: e.params.name,
								coupon_num: 1,
							});
							self.coupon_list.push({
								coupon_id: e.params.coupon_id,
								name: e.params.name,
								coupon_num: 1,
							});
						} else {
							let flag = true;
							self.form.coupon.forEach((item, index) => {
								if (item.coupon_id == e.params.coupon_id) {
									flag = false;
								}
							});
							if (flag) {
								self.form.coupon.push({
									coupon_id: e.params.coupon_id,
									name: e.params.name,
									coupon_num: 1,
								});
								self.coupon_list.push({
									coupon_id: e.params.coupon_id,
									name: e.params.name,
									coupon_num: 1,
								});
							} else {
								ElMessage.error("请勿重复添加");
							}
						}
						console.log(self.coupon_list);
					}
				} else if (self.coupon_name == "coup_sum") {
					if (e.type === "success") {
						// 确保 reward_data 中存在对应索引的 item
						const reward_item = self.form.reward_data[self.coupon_index];
						if (reward_item) {
							if (!Array.isArray(reward_item.coupon)) {
								reward_item.coupon = [];
							}
							const isDuplicate = reward_item.coupon.some(
								(coupon) => coupon.coupon_id === e.params.coupon_id
							);
							if (!isDuplicate) {
								reward_item.coupon.push({
									coupon_id: e.params.coupon_id,
									name: e.params.name,
									coupon_num: 1,
								});
							} else {
								ElMessage.error("请勿重复添加");
							}
						} else {
							ElMessage.error("未找到对应的连续签到规则");
						}
					}
				}
			},
			delcoupon(item) {
				let self = this;
				let n = self.coupon_list.indexOf(item);
				self.coupon_list.splice(n, 1);
				self.form.coupon.splice(n, 1);
			},
			delcoupons(index, coupon_index) {
				this.form.reward_data[index].coupon.splice(coupon_index, 1);
			},
			contentChangeFunc(e) {
				this.ueditor.text = e;
			},
			/*获取列表*/
			getData() {
				let self = this;
				self.loading = true;
				getData()
					.then(data => {
						self.loading = false;
						let val = data.data.vars.values;
						self.form.is_increase = val.is_increase;
						self.form.is_coupon = val.is_coupon;
						self.form.is_open = val.is_open;
						self.form.increase_reward = val.increase_reward;
						self.form.no_increase = val.no_increase;
						self.form.ever_sign = val.ever_sign;
						self.form.sign_type = val.sign_type;
						self.form.coupon = JSON.parse(JSON.stringify(val.coupon));
						self.coupon_list = val.coupon;
						self.contents = val.content;
						self.ueditor.text = val.content;
						if (val.reward_data) {
							let len = val.reward_data.length;
							for (let i = 0; i < len; i++) {
								let item = val.reward_data[i];
								if (item.is_coupon == true) {
									item.is_coupon = true;
								} else {
									item.is_coupon = false;
								}
								if (item.is_point == true) {
									item.is_point = true;
								} else {
									item.is_point = false;
								}
							}
							self.form.reward_data = val.reward_data;
						}
					})
					.catch(error => {});
			},

			/*提交签到有礼*/
			onSubmit() {
				let self = this;
				let params = self.form;
				if (params.is_open) {
					params.content = self.contents;
				}

				self.$refs.ruleForm.validate(valid => {
					if (valid) {
						self.loading = true;
						saveData(params, true)
							.then(data => {
								ElMessage({
									message: '恭喜你，保存成功',
									type: 'success'
								});
								self.getData();

							})
							.catch(error => {
								self.loading = false;
							});
					}
				});
			},

			/*获取富文本编辑器的内容*/
			getContent: function() {
				if (this.editor) {
					return this.editor.getContent();
				} else {
					return ''
				}
				// return this.$refs.ue.getUEContent();
			},

			/*添加奖励*/
			addReward() {
				let obj = {
					day: 0,
					is_point: false,
					point: 0,
					is_coupon: false,
					coupon: []
				};
				this.form.reward_data.push(obj);
			},

			/*删除奖励*/
			deleteRewardClick(e) {
				this.form.reward_data.splice(e, 1);
			}
		}
	};
</script>

<style scoped="scoped">
	.open-sign {
		margin-left: 100px;
		margin-bottom: 10px;
		margin-top: -20px;
	}

	.reward-list .reward-item {
		margin-bottom: 10px;
		padding: 10px 20px 0;
		background-color: rgba(246, 246, 246, 1);
	}

	.reward-list .delete-reward {
		/* position: absolute;
		top: 10px;
		right: 10px;
		z-index: 10; */
		cursor: pointer;
	}

	.el-button--small.is-circle {
		padding: 4px;
	}

	.bg_coupon {
		background-color: rgba(246, 246, 246, 1);
		color: rgba(16, 16, 16, 1);
		font-size: 14px;
		padding: 10px;
	}

	::v-deep .el-input-number .el-input__inner {
		text-align: left;
	}
</style>